/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package fun.tan90.easy.binlog.plugin.kafka.listener;


import cn.hutool.json.JSONUtil;
import com.github.benmanes.caffeine.cache.LoadingCache;
import fun.tan90.easy.binlog.base.enums.OutputResEnum;
import fun.tan90.easy.binlog.base.enums.OutputTypeEnum;
import fun.tan90.easy.binlog.plugin.common.constants.DamiEventConstants;
import fun.tan90.easy.binlog.plugin.common.event.BinlogDataEvent;
import fun.tan90.easy.binlog.plugin.common.event.BinlogDataEventRes;
import fun.tan90.easy.binlog.plugin.common.listener.BinlogEventPluginListener;
import fun.tan90.easy.binlog.plugin.common.model.BinlogData;
import fun.tan90.easy.binlog.plugin.common.model.BinlogOutputRule;
import fun.tan90.easy.binlog.plugin.kafka.constants.KafkaPluginConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.producer.KafkaProducer;
import org.apache.kafka.clients.producer.ProducerRecord;
import org.noear.dami.Dami;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.ApplicationListener;

import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;

/**
 * description 应用初始化后置处理器，防止 spring 事件被多次执行
 * company 铁人科技
 *
 * @author 陈浩杰
 * @date 2022/8/17 8:31
 */
@Slf4j
public class KafkaEventProcessor implements BinlogEventPluginListener, ApplicationListener<ApplicationReadyEvent> {

    private final AtomicBoolean initialized = new AtomicBoolean(false);

    private final LoadingCache<String, KafkaProducer<String, String>> kafkaProducerCache;

    public KafkaEventProcessor(LoadingCache<String, KafkaProducer<String, String>> kafkaProducerCache) {
        this.kafkaProducerCache = kafkaProducerCache;
    }

    @Override
    public void onApplicationEvent(ApplicationReadyEvent event) {
        if (initialized.compareAndSet(false, true)) {
            Dami.<BinlogDataEvent, BinlogDataEventRes>bus().listen(DamiEventConstants.BINLOG_EVENT_TOPIC + outputType(), payload -> {
                BinlogDataEvent binlogDataEvent = payload.getContent();
                String masterCode = binlogDataEvent.getMasterCode();
                List<BinlogData> binlogDataList = binlogDataEvent.getBinlogDataList();
                List<BinlogOutputRule> binlogOutputRules = binlogDataEvent.getBinlogOutputRules();
                for (BinlogOutputRule binlogOutputRule : binlogOutputRules) {
                    String outputRuleCountId = binlogOutputRule.getOutputRuleCountId();
                    String outputCode = binlogOutputRule.getOutputCode();
                    KafkaProducer<String, String> kafkaProducer = kafkaProducerCache.get(outputCode);
                    if (kafkaProducer != null) {
                        for (BinlogData binlogData : binlogDataList) {
                            if (filterOutput(binlogOutputRule, binlogData)) {
                                ProducerRecord<String, String> record = new ProducerRecord<>(KafkaPluginConstants.TOPIC + masterCode, JSONUtil.toJsonStr(binlogData));
                                kafkaProducer.send(record, (metadata, exception) -> {
                                    log.info("onCompletion partition {} offset {}", metadata.partition(), metadata.offset());
                                    if (exception != null) {
                                        reply(payload, outputRuleCountId, OutputResEnum.ERROR);
                                        exception.printStackTrace();
                                    } else {
                                        reply(payload, outputRuleCountId, OutputResEnum.SUCCESS);
                                    }
                                });
                            }
                        }
                    }
                }
            });
        }
    }

    @Override
    public String outputType() {
        return OutputTypeEnum.KAFKA.getOutput();
    }
}
